<?php
//https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html
require_once 'Services/Amazon.php';
require_once 'lib/UserAgentManager.class.php';
require_once 'lib/AmazonAsocUtil.class.php';
function sanitize($str) {
    $vowels = array(";", "|", "\"", "x00", "x08", "x7f", "x20", "x04", "x0D", "x1b", "*", "&lt;", "&gt;", "\'", "../", "./");
    $str = str_replace($vowels, "", $str);
    return $str;
}
// client
// MUST config must move to config.php
$config= array();
$config['amazon_page_limit'] = 10;


$config['deault_search_index'] = 'Electronics';
if($locale == "cn"){
 $config['deault_search_index'] = 'Electronics';

}

$config['meta_title'] = "Associate* | tweet associate link anywhere";
$config['default_locale'] = "jp";

$search_index = $config['deault_search_index'];


if (!isset($locale)) {
    if (!isset($_GET['locale'])) {
        $locale = $config['default_locale'];
    } else {
        $locale =sanitize($_GET['locale']);
    }
}

$amazonAsocUtil = new AmazonAsocUtil();
$userAgentManager = new UserAgentManager();

if (isset($_GET['search_index'])) {
    if (!empty($_GET['search_index'])) {
        $search_index = sanitize($_GET['search_index']);
    }
}

$searchIndexOptions = array();
$searchIndexTag = $amazonAsocUtil->getSearchIndexHtml($searchIndexOptions, $search_index);

// TODO: REFACTORING
$asoc_id = "agniuek-22-22";
if (isset($_GET['asoc_id'])) {
    if (!empty($_GET['asoc_id'])) {
        $asoc_id = $_GET['asoc_id'];
        $_SESSION['asoc_id']=$asoc_id ;
    }
}else{
   if(isset($_SESSION['asoc_id'])) {
       if(!empty($_SESSION['asoc_id'])){
            $asoc_id =$_SESSION['asoc_id'];
       }
   }
}
$asoc_id = sanitize($asoc_id);
// set default
$keywords = "APPLE MacBook Pro with Retina Display";
if($locale == "cn"){
 $keywords = "APPLE MacBook";
}

if (isset($_GET['keywords'])) {
    $keywords = $_GET['keywords'];
}
$keywords = sanitize($keywords);

$itemPage = 1;
if (isset($_GET['itemPage'])) {
    $itemPage = $_GET['itemPage'];
}
$itemPage = sanitize($itemPage);
$amazon = "";
$amazon = new Services_Amazon('AKIAIVUCVEO6SU6NZUFQ', 'OB8IgE4mJC/RWnul3KLHMZA0P2VjNuomZF7+O/zp', $asoc_id);
$options = array();
$options['Keywords'] = "'" . $keywords . "'";
$options['Sort'] = 'salesrank';
$options['ResponseGroup'] = 'ItemIds,ItemAttributes,Images';
$options['ItemPage'] = $itemPage;
$options['AssociateTag'] = $asoc_id;
//$options['locale']=strtoupper($locale);
$searchIndexOptions = $search_index;
$response = null;
$response = $amazonAsocUtil->itemsearch($amazon, $options, $searchIndexOptions, $locale);
$error_essage = "";
if (!is_array($response) && 'PEAR_Error' == get_class($response)) {
    $error_essage = $response->message;
    echo $error_essage;
    echo "<a href='/index.php'>" . "back to top" . "</a>";
}
//print_r($response);
$items = $response['Item'];
$total_result = $response["TotalResults"]; // use at view
$total_pages = intval(($response["TotalPages"]));

$paging_link = "<div id='pagingarea'><ul id='paging'>";

if ($total_pages > $config['amazon_page_limit']) {
    $counter = $config['amazon_page_limit'];
} else {
    $counter = $total_pages;
}

for ($paging = 1; $paging < ($counter + 1); $paging++) {
    $paging_url = "";
    if ($paging == $itemPage) {
        $paging_link.="<li>".$paging . "</li>";
    } else {
        $paging_link.= "<li><a href='/" . $locale . "/index.php?";
        $paging_url.= "itemPage=" . $paging;
        $paging_url.= '&amp;asoc_id=' . $asoc_id;
        $paging_url.= '&amp;keywords=' . $keywords;
        $paging_url.= '&amp;search_index=' . $search_index;
        $paging_url.= '&amp;locale=' . $locale;
        $paging_link.= ($paging_url);
        $paging_link.="'> " . $paging . " </a></li>";
    }
}
$paging_link.="</ul></div>";

$itemsearch_tags = "";
for ($i = 0; $i < count($items); $i++) {
    $image_link = "";
    $asin = $items[$i]['ASIN'];
    $title = $items[$i]['ItemAttributes']['Title'];
    if ($i == 0) {
        //var_dump($items[$i]);
    }
    $small_image = $items[$i]['SmallImage'];
    $small_image_url = $small_image['URL'];
    $detail_page_url = $items[$i]['DetailPageURL'];

    $itemsearch_tags.="<div>";
    $itemsearch_tags.= "asin:$asin ";
    $itemsearch_tags.= "<label for='". "text_link_$asin" ."'> text link:</label>";
    $itemsearch_tags.= "<a href='" . $detail_page_url . "'" . " ><p>$title</p></a><br />";

    $itemsearch_tags.= "<textarea rows='2' data-mini='true' cols='10' class='tarea' id='text_link_" . $asin . "'" . " onclick='this.focus();this.selectionstart=0;this.selectionEnd=this.value.length;' " . ">";
    $itemsearch_tags.= "<a href='" . $detail_page_url . "'" . " ><p>$title</p></a>";
    $itemsearch_tags.="</textarea>";
    $itemsearch_tags.="</div>";

    // twitter
    $twtag = "";
    $twtag.= "<iframe height='45' width='90' style='overflow:hidden;border:none;'  src='/sns.php?" . "u=" . urlencode($detail_page_url) . "&amp;" . "t=" . urlencode($title) . "'>";
    $twtag.="</iframe>";
    $itemsearch_tags.=$twtag;

    //image link
    // FIXME detail_page_url can't use urlencode
    $image_link.="<a href='" . $detail_page_url . "'" . ">";
    $image_link.= "<img src='"
            . $small_image_url . "'"
            . " alt='" . htmlspecialchars($title) . "'"
            . " /></a>";
    // textarea image link
    $itemsearch_tags.= "<div>";
    $itemsearch_tags.=" <p>image link:</p>";
    $itemsearch_tags.= $image_link;
    $itemsearch_tags.="  <textarea rows='2' cols='10' id='small_image_" . $asin . "'" . " onclick='this.focus();this.selectionstart=0;this.selectionEnd=this.value.length;' " . ">";
    $itemsearch_tags.= $image_link;
    $itemsearch_tags.="  </textarea>";
    $itemsearch_tags.=" </div>";
    $itemsearch_tags.="  <hr class='split'/>";
}
//$iteamsearch_tags.= "</ul>";
if ($asoc_id == 'agniuek-22-22') {
    $asoc_id = "";
}


// TODO: NEED WRAP
  // Copyright 2009 Google Inc. All Rights Reserved.
  $GA_ACCOUNT = "UA-38811559-1";
  $GA_PIXEL = "/ga.php";

  function googleAnalyticsGetImageUrl() {
    global $GA_ACCOUNT, $GA_PIXEL;
    $url = "";
    $url .= $GA_PIXEL . "?";
    $url .= "utmac=" . $GA_ACCOUNT;
    $url .= "&utmn=" . rand(0, 0x7fffffff);

    $referer = $_SERVER["HTTP_REFERER"];
    $query = $_SERVER["QUERY_STRING"];
    $path = $_SERVER["REQUEST_URI"];

    if (empty($referer)) {
      $referer = "-";
    }
    $url .= "&utmr=" . urlencode($referer);

    if (!empty($path)) {
      $url .= "&utmp=" . urlencode($path);
    }

    $url .= "&guid=ON";

    return str_replace("&", "&amp;", $url);
  }


// dispatch
if ($userAgentManager->is_smartphone()) {
    require_once ('index_view_sm.php');
} elseif ($userAgentManager->isDoComo() || $userAgentManager->isEZweb()) {
    require_once ('index_view_sjis.php');
} else {
    require_once ('index_view_sm.php');
}
?>
